<?php
declare (strict_types = 1);

namespace app\middleware;

use Closure;
use think\Config;
use think\Request;
use think\Response;

class AllowCrossDomain
{

    protected $cookieDomain;

    // header头配置
    protected $header = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => 1800,
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers'     => 'Origin, X-Requested-With, Content-Type, Accept,Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, X-Token,token',
        ];


    /**
     * AllowCrossDomain constructor.
     * @param Config $config
     */
    public function __construct(Config $config)
    {
        $this->cookieDomain = $config->get('cookie.domain', '');
    }

    /**
     * 允许跨域请求
     * @access public
     * @param Request $request
     * @param Closure $next
     * @param array   $header
     * @return Response
     */
    public function handle($request, Closure $next, ?array $header = [])
    {
        // 设置允许跨域的域名，* 代表允许任意域名跨域访问
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: *');
        header('Access-Control-Allow-Headers: *');
        header('Access-Control-Allow-Credentials: true');

        // 如果是 OPTIONS 请求，直接返回
        if (request()->isOptions()) {
            return response()->code(200);
        }

        return $next($request)->header($header);
    }
}
